/**
 * FileResourceHover.java
 * created by wesley at 2008-6-7
 */
package net.sf.filelink.hover;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import net.sf.filelink.utl.QueryUtils;
import net.sf.filelink.utl.XmlEditorUtils;

import org.eclipse.core.resources.IFile;
import org.eclipse.jface.internal.text.html.HTMLPrinter;
import org.eclipse.jface.text.DefaultTextHover;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.source.ISourceViewer;
import org.w3c.dom.Node;

/**
 * FileResourceHover
 * 
 * @author wesley
 */
public class FileResourceHover extends DefaultTextHover {

	/**
	 * constructor for FileReso urceHover
	 * 
	 * @param sourceViewer
	 */
	public FileResourceHover(ISourceViewer sourceViewer) {
		super(sourceViewer);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.jface.text.DefaultTextHover#getHoverInfo(org.eclipse.jface
	 * .text.ITextViewer, org.eclipse.jface.text.IRegion)
	 */
	@Override
	public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {

		int offset = hoverRegion.getOffset();
		Node node = XmlEditorUtils.getNodeByOffset(textViewer.getDocument(),
				offset);

		if (node != null
				&& (node.getNodeType() == Node.TEXT_NODE || node.getNodeType() == Node.ATTRIBUTE_NODE)) {

			String nodeInfo = node.getNodeValue();
			if (nodeInfo != null) {
				nodeInfo = nodeInfo.trim();
			}

			Set<String> filePathSets = new LinkedHashSet<String>();

			// search file by path
			String filePath = QueryUtils.toFilePath(nodeInfo);
			List<IFile> fileList = QueryUtils.findFileResources(filePath,
					QueryUtils.getSearchFolders());
			for (IFile file : fileList) {
				String fileInfo = file.getProjectRelativePath().toString();
				filePathSets.add(fileInfo);
			}

			// search file by name
			String fileName = QueryUtils.toFileName(nodeInfo);
			if (!fileName.equals(filePath)) {
				fileList = QueryUtils.findFileResources(fileName, QueryUtils
						.getSearchFolders());
				for (IFile file : fileList) {
					String fileInfo = file.getProjectRelativePath().toString();
					filePathSets.add(fileInfo);
				}
			}

			StringBuffer infoBuff = new StringBuffer();
			HTMLPrinter.addPageProlog(infoBuff);
			HTMLPrinter.addParagraph(infoBuff, "Files:");
			infoBuff.append("</p>");

			HTMLPrinter.startBulletList(infoBuff);

			for (String filePathItem : filePathSets) {
				HTMLPrinter.addBullet(infoBuff, HTMLPrinter
						.convertToHTMLContent(filePathItem));
			}

			HTMLPrinter.endBulletList(infoBuff);

			HTMLPrinter.addPageEpilog(infoBuff);

			return infoBuff.toString();
		} else {
			return null;
		}
	}
}
